import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:flutter/services.dart';

import 'package:flutter/material.dart';
import 'package:flutter_reader/dao/book_collect_data_manager.dart';
import 'package:flutter_reader/pages/Login/login_page.dart';
import 'package:flutter_reader/pages/read_book/book_introduction.dart';
import 'package:flutter_reader/tools/nav_animation.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_reader/dao/login_data_manager.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:crypto/crypto.dart' as crypto;
import 'package:flutter_reader/tools/globals.dart' as globals;
import 'package:overlay_support/overlay_support.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginNavPage extends StatefulWidget {
  LoginNavPage({Key key}) : super(key: key);

  @override
  _LoginNavPageState createState() {
    return _LoginNavPageState();
  }
}

class _LoginNavPageState extends State<LoginNavPage> {
  String state = '';
  String _udid = 'Unknown';
  @override
  void initState() {
    // initPlatformState();
    super.initState();
    getAppID();
  }

  @override
  void dispose() {
    super.dispose();
  }

  ///集成极光推送
  String debugLable = 'Unknown';
  // final JPush jpush = new JPush();

  // Future<void> initPlatformState() async {
  //   String platformVersion;
  //   try {
  //     jpush.addEventHandler(
  //       onOpenNotification: (Map<String, dynamic> message) async {
  //         print('通知栏打开');
  //         print("flutter onOpenNotification: $message");
  //         print("${message["extras"]}");
  //         print("${message["extras"]["cn.jpush.android.EXTRA"]}");
  //         Map aa = json.decode(message["extras"]["cn.jpush.android.EXTRA"]);
  //         print("${aa["bookID"]}");
  //         Navigator.push(context, MaterialPageRoute(
  //             builder: (context) => BookInfoPage(bookId: aa["bookID"],channel: "1",)
  //         ));
  //       },
  //     );
  //   } on PlatformException {
  //     platformVersion = 'Failed to get platform version.';
  //   }
  // }

  generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var md5 = crypto.md5;
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }

  ///动态获取AppId
  getAppID(){
    LoginDao.fetchAppID(globals.dateError).then((value){
      _initFluwx(value['data']['appid']);
      state = value['data']['state'];
    });
  }

  ///fluwx需要初始化
  _initFluwx(String appid) async{
    await fluwx.registerWxApi(appId: appid,doOnAndroid: true,doOnIOS: true);
  }

  ///微信登录
  _wechatLogin(){

  }

  saveData(String sessionID) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    preferences.setString('login', 'true');
    preferences.setString('fullSessionID', sessionID);
    preferences.setString('LoginDate', DateTime.now().toIso8601String());
    print(DateTime.now().toIso8601String());
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Container(
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          color: Colors.lightBlueAccent,
          image: DecorationImage(
            colorFilter: new ColorFilter.mode(
                Colors.black.withOpacity(0.2), BlendMode.dstATop),
            image: AssetImage('images/fl_bgImage.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: ScreenUtil().setHeight(700)),
              child: Center(
                child: Image(
                  fit: BoxFit.fill,
                  width: ScreenUtil().setWidth(170),
                  image: AssetImage('images/fl_readBook.png'),
                ),
              ),
            ),
            Container(
              padding: EdgeInsets.only(top: ScreenUtil().setHeight(20)),
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text(
                    "爱看",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: ScreenUtil().setSp(60),
                    ),
                  ),
                  Text(
                    "App",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: ScreenUtil().setSp(60),
                        fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
            new Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(100), right: ScreenUtil().setWidth(100), top: ScreenUtil().setHeight(600)),
              alignment: Alignment.center,
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    child: new FlatButton(
                      shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0)),
                      color: Colors.white,
                      onPressed: (){
                        ///fluwx获取code
                        fluwx.sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test");
                        fluwx.responseFromAuth.listen((response) {
                          //监听授权登录回调
                          print("ErrCode:${response.errCode}");
                          print("code: " + response.code);
                          LoginDao.wechatLogin(globals.dateError, response.code, state).then((value){
                            print(value);
                            if(value['success'] == true)
                              {
                                getUdid();
                                globals.fullSessionID = value['data']['SessionID'];
                                saveData(value['data']['SessionID']);
                                configDialog();
                                addRecommendBook();
                              }
                            else
                              {
                                toast('登录失败');
                              }
                          });
                        });
                      },
                      child: new Container(
                        height: ScreenUtil().setHeight(130),
                        child: new Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Container(
                                child: Image(
                                  fit: BoxFit.fill,
                                  width: ScreenUtil().setWidth(100),
                                  image: AssetImage('images/fl_wechat2.png'),
                                )
                            ),
                            new Container(
                              margin: EdgeInsets.only(left: ScreenUtil().setWidth(40)),
                              child: Text(
                                "微信登录",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: ScreenUtil().setSp(45),
                                    color: Colors.greenAccent,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            new Container(
              width: MediaQuery.of(context).size.width,
              margin: EdgeInsets.only(left: ScreenUtil().setWidth(100), right: ScreenUtil().setWidth(100), top: ScreenUtil().setHeight(100)),
              alignment: Alignment.center,
              child: new Row(
                children: <Widget>[
                  new Expanded(
                    child: new OutlineButton(
                      shape: new RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0)),
                      borderSide: BorderSide(width: 3,color: Colors.white),
                      color: Colors.white,
                      highlightedBorderColor: Colors.white,
                      onPressed: (){
                        Navigator.push(context, ScaleRoute(page: LoginPage()));
                      },
                      child: new Container(
                        height: ScreenUtil().setHeight(130),
                        child: new Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            new Expanded(
                              child: Text(
                                "手机号快速登录",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: Colors.white,
                                    fontSize: ScreenUtil().setSp(45),
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        )
      ),
    );
  }

  addRecommendBook() async{
    print("添加推荐书");
    BookCollectDao.getForCollect("84101F8BF73334E10D400EAAE33FB71B");
    Future.delayed(const Duration(milliseconds: 100), (){
      BookCollectDao.getForCollect("34F73CA6C7AC6C6A2B54465AB251CAE0");
      Future.delayed(const Duration(milliseconds: 100),(){
        BookCollectDao.getForCollect("D2E941B0E38A097A110A920CB0B9C475");
      });
    });
    Navigator.of(context).popUntil((route) => route.isFirst);
  }

  configDialog() async{
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    //弹窗倒计时
    sharedPreferences.setInt("dialog", 2);
    sharedPreferences.setBool("goOther", false);
  }

  Future<void> getUdid() async {
    String udid;
    try {
      udid = await FlutterUdid.udid;
    } on
    PlatformException {
      udid = 'Failed to get UDID.';
    }
    _udid = udid;
    print('udid:${_udid}');
    globals.uuid = _udid;
  }
}